package com.jl.cloud.gateway.filter;

import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.UUID;

@Component
@Order(-1)
public class TraceIdFilter implements GlobalFilter {

    private final String traceIdKey = "traceId";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        List<String> traceIds = request.getHeaders().get(traceIdKey);
        //判断是否有traceId
        if (traceIds != null && !traceIds.isEmpty()) {
            // 放行
            MDC.put(traceIdKey, traceIds.get(0));
            return chain.filter(exchange);
        }
        //为空，生成一个traceId
        String traceId = String.valueOf(UUID.randomUUID());
        // 创建新的请求
        ServerHttpRequest newRequest = request.mutate().header(traceIdKey, traceId).build();
        // 创建新的exchange
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        // 放行
        MDC.put(traceIdKey,traceId);
        return chain.filter(newExchange);
    }
}
